<script setup lang="ts">
import { getPatientList, addPatient, editPatient, delPatient } from '@/api/user'
import type { PatientList, Patient } from '@/types/user'
import { showFailToast, showSuccessToast, showConfirmDialog, showToast } from 'vant'
import { onMounted, ref, watch, computed } from 'vue'
// 导入校验身份证格式的插件
import Validator from 'id-validator'
import { useRoute, useRouter } from 'vue-router'
import { useConsultStore } from '@/stores'
// 准备默认值
const initPatient: Patient = {
  name: '',
  idCard: '',
  gender: 1,
  defaultFlag: 0 //1是默认 0 非默认
}
//新增患者表单数据，后台返回
const patient = ref<Patient>({ ...initPatient })
// 是否是默认患者，患者选择
const defaultFlag = ref(false)
// 监控defaultFlag变化，将defaultFlag选中的boolean值转换成0|1
watch(defaultFlag, () => {
  console.log('defaultFlag.value', defaultFlag.value)
  console.log('patient.value.defaultFlag', patient.value.defaultFlag)
  patient.value.defaultFlag = defaultFlag.value ? 1 : 0
  console.log(patient.value.defaultFlag)
})
// 1. 查询家庭档案-患者列表
const patientlist = ref<PatientList>([])
// 2.定义获取数据的方法
const getPatientListData = async () => {
  const { data: res } = await getPatientList()
  console.log(res, '=患者列表')
  patientlist.value = res
  // 设置默认选中的ID，当可选状态，且有患者时
  if (isSelect.value && res.length > 0) {
    const defPatient = res.find((item: { defaultFlag: number }) => item.defaultFlag === 1)
    if (defPatient) patientId.value = defPatient.id
    else patientId.value = res[0].id
  }
}
onMounted(() => {
  getPatientListData()
})
// 2. 打开侧滑栏
const show = ref(false)
const showPopup = (item?: Patient) => {
  if (item) {
    console.log(111, item)
    const { id, gender, name, idCard, defaultFlag } = item
    patient.value = { id, gender, name, idCard, defaultFlag }
  } else {
    patient.value = { ...initPatient }
  }
  show.value = true
}
// 性别选项
const options = [
  { label: '男', value: 1 },
  { label: '女', value: 0 }
]
// const gender = ref(1)
// 2.保存患者信息
const validate = new Validator()
const submit = async () => {
  if (!patient.value.name) return showFailToast('请输入真实姓名')
  if (!patient.value.idCard) return showFailToast('请输入身份证号')
  if (!validate.isValid(patient.value.idCard)) return showFailToast('身份证格式错误')
  const { sex } = validate.getInfo(patient.value.idCard)
  if (patient.value.gender !== sex) return showFailToast('性别和身份证不符')
  try {
    console.log('可以新增了')
    patient.value.id ? await editPatient(patient.value) : await addPatient(patient.value)
    show.value = false
    getPatientListData()
    showSuccessToast('添加成功')
  } catch (err) {
    console.log(err)
  }
}
// 3.删除
const remove = async () => {
  if (patient.value.id) {
    await showConfirmDialog({
      title: '温馨提示',
      message: `您确认要删除 ${patient.value.name} 患者信息吗 ？`
    })
    await delPatient(patient.value.id)
    show.value = false
    getPatientListData()
    showSuccessToast('删除成功')
  }
}

// 是否是:选择患者
const route = useRoute()
const isSelect = computed(() => route.query.isSelect === '1')

// 存储点击选中患者ID作为标识
const patientId = ref<string>()
const selectedPatient = (item: Patient) => {
  if (isSelect.value) {
    patientId.value = item.id
  }
}

// 4.记录患者ID跳转到待支付页面
const store = useConsultStore()
const router = useRouter()
const next = async () => {
  if (!patientId.value) return showToast('请选问诊择患者')
  store.setPatient(patientId.value)
  router.push('/consult/pay')
}
</script>

<template>
  <div class="patient-page">
    <cp-nav-bar :title="isSelect ? '选择患者' : '家庭档案'" />
    <!-- 头部选择提示 -->
    <div class="patient-change" v-if="isSelect">
      <h3>请选择患者信息</h3>
      <p>以便医生给出更准确的治疗，信息仅医生可见</p>
    </div>
    <div class="patient-list">
      <div
        class="patient-item"
        v-for="item in patientlist"
        :key="item.id"
        @click="selectedPatient(item)"
        :class="{ selected: patientId === item.id }"
      >
        <div class="info">
          <span class="name">{{ item.name }}</span>
          <!-- 身份证号脱敏处理 -->
          <span class="id">{{ item.idCard.replace(/^(.{6})(?:\d+)(.{4})$/, '\$1******\$2') }}</span>
          <span>{{ item.genderValue }}</span>
          <span>{{ item.age }}岁</span>
        </div>
        <div class="icon" @click="showPopup(item)">
          <cp-icon name="user-edit" />
        </div>
        <div class="tag" v-if="item.defaultFlag === 1">默认</div>
      </div>
      <div @click="showPopup()" class="patient-add" v-if="patientlist.length < 6">
        <cp-icon name="user-add" />
        <p>添加患者</p>
      </div>
      <div class="patient-tip">最多可添加 6 人</div>
    </div>
    <!-- 患者选择下一步 -->
    <div class="patient-next" v-if="isSelect">
      <van-button type="primary" @click="next" round block>下一步</van-button>
    </div>
    <!-- 新增患者弹层 -->
    <van-popup v-model:show="show" position="left">
      <cp-nav-bar
        :title="patient.id ? '编辑患者' : '添加患者'"
        right-text="保存"
        @click-right="submit"
        :back="() => (show = false)"
      ></cp-nav-bar>
      <!-- 新增患者表单 -->
      <van-form autocomplete="off" style="padding-top: 46px">
        <van-field v-model="patient.name" label="真实姓名" placeholder="请输入真实姓名" />
        <van-field v-model="patient.idCard" label="身份证号" placeholder="请输入身份证号" />
        <van-field label="性别">
          <!-- 单选按钮组件 -->
          <template #input>
            <cp-radio-btn :options="options" v-model="patient.gender" />
          </template>
        </van-field>
        <van-field label="默认就诊人">
          <template #input>
            <!-- 说明：直接绑定存储的是boolean值 -->
            <!-- 使用计算属性转换 -->
            <van-checkbox round v-model="defaultFlag" />
          </template>
        </van-field>
      </van-form>
      <van-action-bar>
        <van-action-bar-button @click="remove" type="danger" text="删除"></van-action-bar-button>
      </van-action-bar>
    </van-popup>
  </div>
</template>

<style lang="scss" scoped>
.patient-page {
  padding: 46px 0 80px;
  ::v-deep() {
    .van-popup {
      width: 100%;
      height: 100%;
    }
  }
}
.patient-change {
  padding: 15px;
  > h3 {
    font-weight: normal;
    margin-bottom: 5px;
  }
  > p {
    color: var(--cp-text3);
  }
}
.patient-next {
  padding: 15px;
  background-color: #fff;
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 80px;
  box-sizing: border-box;
}
.patient-list {
  padding: 15px;
}
.patient-item {
  display: flex;
  align-items: center;
  padding: 15px;
  background-color: var(--cp-bg);
  border-radius: 8px;
  margin-bottom: 15px;
  position: relative;
  border: 1px solid var(--cp-bg);
  transition: all 0.3s;
  overflow: hidden;
  .info {
    display: flex;
    flex-wrap: wrap;
    flex: 1;
    span {
      color: var(--cp-tip);
      margin-right: 20px;
      line-height: 30px;
      &.name {
        font-size: 16px;
        color: var(--cp-text1);
        width: 80px;
        margin-right: 0;
      }
      &.id {
        color: var(--cp-text2);
        width: 180px;
      }
    }
  }
  .icon {
    color: var(--cp-tag);
    width: 20px;
    text-align: center;
  }
  .tag {
    position: absolute;
    right: 60px;
    top: 21px;
    width: 30px;
    height: 16px;
    font-size: 10px;
    color: #fff;
    background-color: var(--cp-primary);
    border-radius: 2px;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  &.selected {
    border-color: var(--cp-primary);
    background-color: var(--cp-plain);
    .icon {
      color: var(--cp-primary);
    }
  }
}
.patient-add {
  background-color: var(--cp-bg);
  color: var(--cp-primary);
  text-align: center;
  padding: 15px 0;
  border-radius: 8px;
  .cp-icon {
    font-size: 24px;
  }
}
.patient-tip {
  color: var(--cp-tag);
  padding: 12px 0;
}
</style>
